import { TaskCmd } from "../../constants/command";
import { spawn } from "node:child_process";
import { logger } from "../log";
type Handler = {
  onData?: (str: string) => void;
};

/**
 * 负责执行传入的任务
 */
export class TaskExecutor {
  exec(param: TaskCmd, handler?: Handler) {
    const { cwd, cmd } = param;
    return new Promise((resolve, reject) => {
      // 放慢速度
      const cp = spawn("cmd", ["/c", cmd], {
        stdio: "pipe",
        timeout: 1000 * 60 * 20,
        cwd,
      });

      cp.stdout.on("data", (val) => {
        const data = val.toString();
        logger.debug(data)
        handler?.onData?.(data);
      });
      cp.stderr.on("data", (err) => {
        logger.warn("Runtime Error:", err.toString());
      });
      cp.on("error", (err) => {
        reject(err.message);
      });

      cp.on("exit", (code, signal) => {
        if (code) {
          reject(`Exit code:${code} signal: ${signal}`);
        } else {
          resolve(true);
        }
      });
    });
  }
}

export const taskExecutor = new TaskExecutor();
